/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.extra.tags;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import org.gidoo.cms.login.GidooCMSSession;

/**
 *
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 */
public class Helper
{

  public static Set<String> getAllsTagsOfSite(GidooCMSSession session)
  {
    HashSet<String> result = new HashSet<String>();
    try
    {
      
      QueryManager qm = session.getQueryManager();
      Query q = qm.createQuery("/jcr:root/sections//cms:md/tags/*", Query.XPATH);
      NodeIterator itAllTags = q.execute().getNodes();

      while(itAllTags.hasNext())
      {
        result.add(itAllTags.nextNode().getName());
      }

    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    return result;
  }
  
  public static List<String> getTagsOfPage(Node page)
  {
    LinkedList<String> result = new LinkedList<String>();
      
    try
    {
      Node md = page.getNode("cms:md");

      if(md.hasNode("tags"))
      {

        NodeIterator itOwnTags = md.getNode("tags").getNodes();

        while(itOwnTags.hasNext())
        {
          result.add(itOwnTags.nextNode().getName());
        }
      }
      
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    return result;
  }
}
